package com.huhu.myharmony.ble.slice;

import com.huhu.myharmony.BaseAbilitySlice;
import com.huhu.myharmony.ResourceTable;
import com.huhu.myharmony.ble.BleAbility;
import com.huhu.myharmony.ble.ProtocolEntity;
import com.huhu.myharmony.ble.controller.BleHelper;
import com.huhu.myharmony.utils.Toast;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bluetooth.ProfileBase;
import ohos.bluetooth.ble.*;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;

import java.util.ArrayList;
import java.util.List;

public class BleAbilitySlice extends BaseAbilitySlice implements BleHelper.BleManagerCallback {
    // ABILITY_NAME开发者需要替换为自己项目对应的名称
    private static final String CENTRAL_ABILITY_NAME = "com.huhu.myharmony.ble.slice.BleAbilitySlice";

    private boolean isScanning = false;
    private static final int STOP_SCAN = 110;
    private static final int STATE_CONNECTED = 110;
    private Image back;
    private Button connectButton;
    private DirectionalLayout dlPlugIn;

    // 创建扫描过滤器
    private List<BleScanFilter> filters = new ArrayList<>();
    private Text sensorTv;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_ble);
        BleAbility bleAbility = (BleAbility) getAbility();
        bleAbility.setBleAbilitySlice(this);
        initView();
        initListener();
        BleHelper.getInstance().registerBleManagerCallback(this);
    }

    private void initView() {
        back = (Image) findComponentById(ResourceTable.Id_back);
        connectButton = (Button) findComponentById(ResourceTable.Id_connect);
        dlPlugIn = (DirectionalLayout) findComponentById(ResourceTable.Id_dlPlugIn);
        sensorTv = (Text) findComponentById(ResourceTable.Id_sensor);
    }


    private void initListener() {
        back.setClickedListener(component -> terminate());
        connectButton.setClickedListener(component -> {
                    if (BleHelper.getInstance().isConnected) {
                        showProgress(true);
                        BleHelper.getInstance().disconnect();
                    }else {
                        isScanning = false;
                        sensorTv.setText("火焰传感器(连接中...)");
                        BleHelper.getInstance().disconnect();
                        startOrStopScan();
                    }
                }
        );
        dlPlugIn.setClickedListener(component ->
                present(new BleDetailAbilitySlice(), new Intent())
        );

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public void startOrStopScan() {

        if (!isScanning) {
            isScanning = true;
            showProgress(true);
            // 开始扫描带有过滤器的指定BLE设备
//            BleScanFilter bleScanFilter = new BleScanFilter();
//            bleScanFilter.setPeripheralName("Hi-");
//            filters.add(bleScanFilter);
            BleHelper.getInstance().startScan(filters);
            HiLog.debug(loglabel, "开始扫描设备 startOrStopScan()");

            TimeOutHandle(30 * 1000);
        } else {
            showProgress(false);
            isScanning = false;
            BleHelper.getInstance().stopScan();
            HiLog.debug(loglabel, "停止扫描设备 startOrStopScan()");
        }
    }

    private void TimeOutHandle(int timeOut) {
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).delayDispatch(() -> {
            myEventHandler.sendEvent(STOP_SCAN);
        }, timeOut);
    }

    private final EventHandler myEventHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            switch (event.eventId) {
                case STOP_SCAN:
                    showProgress(false);
                    isScanning = false;
                    BleHelper.getInstance().stopScan();
                    break;
                case ProfileBase.STATE_CONNECTED:
                    connectButton.setText("断开");
                    String deviceName = (String) event.object;
                    Toast.makeToast(getContext(), deviceName + "连接成功", Toast.TOAST_SHORT).show();
                    sensorTv.setText("火焰传感器(已连接)");
                    showProgress(false);
                    break;
                case ProfileBase.STATE_DISCONNECTED:
                    connectButton.setText("连接");
                    Toast.makeToast(getContext(),  "连接断开", Toast.TOAST_SHORT).show();
                    sensorTv.setText("火焰传感器(未连接)");
                    showProgress(false);
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    public void scanResultCallback(BleScanResult var1) {

    }

    @Override
    public void connectCallback(int var1, String deviceName) {
        switch (var1) {
            case ProfileBase.STATE_CONNECTED:
                InnerEvent normalInnerEvent = InnerEvent.get(ProfileBase.STATE_CONNECTED, 0, deviceName);
                myEventHandler.sendEvent(normalInnerEvent);
                myEventHandler.removeEvent(STOP_SCAN);
                break;
            case ProfileBase.STATE_DISCONNECTED:
                myEventHandler.sendEvent(ProfileBase.STATE_DISCONNECTED);

                break;
            default:
                break;
        }
    }

    @Override
    public void characteristicChangedCallback(ProtocolEntity protocolEntity, String hexStr) {

    }

    @Override
    public void characteristicWriteCallback(String hexStr) {

    }
}
